import React, { useState, useCallback } from 'react';
import { Table, Input, Typography } from '@douyinfe/semi-ui';

interface ZhibiaoData {
  ph?: string;
  cod?: string;
  bod?: string;
  ss?: string;
  nh3n?: string;
  tn?: string;
  tp?: string;
  oil?: string;
  ecoli?: string;
}

interface QuchulyItem {
  unit: string;
  zhibiao: {
    jinzhui?: ZhibiaoData;
    chushui?: ZhibiaoData;
    quchulv?: ZhibiaoData;
  };
}

interface Props {
  data: {
    quchuly: QuchulyItem[];
  };
  onDataChange?: (updatedData: QuchulyItem[]) => void;
}

const { Text } = Typography;

export default function RemovalTable({ data, onDataChange }: Props) {
  const [editingCell, setEditingCell] = useState<string | null>(null);
  const [tempValue, setTempValue] = useState<string>('');

  const handleCellEdit = useCallback(
    (
      rowIndex: number,
      field: string,
      subField: string | null,
      value: string
    ) => {
      const newData = { ...data };
      const targetRow = newData.quchuly[rowIndex];

      if (subField) {
        if (!targetRow.zhibiao[field as keyof typeof targetRow.zhibiao]) {
          targetRow.zhibiao[field as keyof typeof targetRow.zhibiao] = {};
        }
        (
          targetRow.zhibiao[
            field as keyof typeof targetRow.zhibiao
          ] as ZhibiaoData
        )[subField as keyof ZhibiaoData] = value;
      } else {
        (targetRow as any)[field] = value;
      }

      onDataChange?.(newData.quchuly);

      setEditingCell(null);
    },
    [data, onDataChange]
  );

  // 开始编辑
  const startEdit = useCallback(
    (
      rowIndex: number,
      field: string,
      subField: string | null,
      currentValue: string
    ) => {
      setEditingCell(`${rowIndex}-${field}-${subField || ''}`);
      setTempValue(currentValue);
    },
    []
  );

  // 取消编辑
  const cancelEdit = useCallback(() => {
    setEditingCell(null);
    setTempValue('');
  }, []);

  // 确认编辑
  const confirmEdit = useCallback(
    (rowIndex: number, field: string, subField: string | null) => {
      handleCellEdit(rowIndex, field, subField, tempValue);
    },
    [handleCellEdit, tempValue]
  );

  // 渲染可编辑单元格
  const renderEditableCell = (
    value: string | undefined,
    rowIndex: number,
    field: string,
    subField: string | null = null
  ) => {
    const cellKey = `${rowIndex}-${field}-${subField || ''}`;
    const isEditing = editingCell === cellKey;

    if (isEditing) {
      return (
        <Input
          value={tempValue}
          onChange={setTempValue}
          onBlur={() => confirmEdit(rowIndex, field, subField)}
          onEnterPress={() => confirmEdit(rowIndex, field, subField)}
          onKeyDown={(e) => {
            if (e.key === 'Escape') {
              cancelEdit();
            }
          }}
          autoFocus
          size="small"
          className="min-w-20"
        />
      );
    }

    return (
      <Text
        onClick={() => startEdit(rowIndex, field, subField, value || '')}
        className="block min-h-5 cursor-pointer rounded px-1 py-0.5 transition-colors duration-200 hover:bg-gray-50"
      >
        {value || '-'}
      </Text>
    );
  };

  // 构建表格数据
  const tableData =
    data?.quchuly?.map((item, index) => ({
      key: index,
      unit: item.unit,
      ...item.zhibiao,
    })) || [];

  // 表格列定义
  const columns = [
    {
      title: '处理单元',
      dataIndex: 'unit',
      key: 'unit',
      width: 200,
      fixed: 'left' as const,
      render: (text: string, record: any, index: number) =>
        renderEditableCell(text, index, 'unit'),
    },
    {
      title: '',
      dataIndex: 'type',
      key: 'type',
      width: 80,
      render: () => (
        <div>
          <div className="mb-2 text-xs">进水</div>
          <div className="mb-2 text-xs">出水</div>
          <div className="text-xs">去除率 (%)</div>
        </div>
      ),
    },
    {
      title: 'PH',
      dataIndex: 'ph',
      key: 'ph',
      width: 100,
      render: (text: string, record: any, index: number) => (
        <div>
          <div className="mb-2 min-h-5">
            {renderEditableCell(record.jinzhui?.ph, index, 'jinzhui', 'ph')}
          </div>
          <div className="mb-2 min-h-5">
            {renderEditableCell(record.chushui?.ph, index, 'chushui', 'ph')}
          </div>
          <div className="min-h-5">
            {renderEditableCell(record.quchulv?.ph, index, 'quchulv', 'ph')}
          </div>
        </div>
      ),
    },
    {
      title: 'COD (mg/L)',
      dataIndex: 'cod',
      key: 'cod',
      width: 120,
      render: (text: string, record: any, index: number) => (
        <div>
          <div className="mb-2 min-h-5">
            {renderEditableCell(record.jinzhui?.cod, index, 'jinzhui', 'cod')}
          </div>
          <div className="mb-2 min-h-5">
            {renderEditableCell(record.chushui?.cod, index, 'chushui', 'cod')}
          </div>
          <div className="min-h-5">
            {renderEditableCell(record.quchulv?.cod, index, 'quchulv', 'cod')}
          </div>
        </div>
      ),
    },
    {
      title: 'BOD (mg/L)',
      dataIndex: 'bod',
      key: 'bod',
      width: 120,
      render: (text: string, record: any, index: number) => (
        <div>
          <div className="mb-2 min-h-5">
            {renderEditableCell(record.jinzhui?.bod, index, 'jinzhui', 'bod')}
          </div>
          <div className="mb-2 min-h-5">
            {renderEditableCell(record.chushui?.bod, index, 'chushui', 'bod')}
          </div>
          <div className="min-h-5">
            {renderEditableCell(record.quchulv?.bod, index, 'quchulv', 'bod')}
          </div>
        </div>
      ),
    },
    {
      title: 'SS (mg/L)',
      dataIndex: 'ss',
      key: 'ss',
      width: 120,
      render: (text: string, record: any, index: number) => (
        <div>
          <div className="mb-2 min-h-5">
            {renderEditableCell(record.jinzhui?.ss, index, 'jinzhui', 'ss')}
          </div>
          <div className="mb-2 min-h-5">
            {renderEditableCell(record.chushui?.ss, index, 'chushui', 'ss')}
          </div>
          <div className="min-h-5">
            {renderEditableCell(record.quchulv?.ss, index, 'quchulv', 'ss')}
          </div>
        </div>
      ),
    },
    {
      title: 'NH3-N (mg/L)',
      dataIndex: 'nh3n',
      key: 'nh3n',
      width: 130,
      render: (text: string, record: any, index: number) => (
        <div>
          <div className="mb-2 min-h-5">
            {renderEditableCell(record.jinzhui?.nh3n, index, 'jinzhui', 'nh3n')}
          </div>
          <div className="mb-2 min-h-5">
            {renderEditableCell(record.chushui?.nh3n, index, 'chushui', 'nh3n')}
          </div>
          <div className="min-h-5">
            {renderEditableCell(record.quchulv?.nh3n, index, 'quchulv', 'nh3n')}
          </div>
        </div>
      ),
    },
    {
      title: 'TN (mg/L)',
      dataIndex: 'tn',
      key: 'tn',
      width: 120,
      render: (text: string, record: any, index: number) => (
        <div>
          <div className="mb-2 min-h-5">
            {renderEditableCell(record.jinzhui?.tn, index, 'jinzhui', 'tn')}
          </div>
          <div className="mb-2 min-h-5">
            {renderEditableCell(record.chushui?.tn, index, 'chushui', 'tn')}
          </div>
          <div className="min-h-5">
            {renderEditableCell(record.quchulv?.tn, index, 'quchulv', 'tn')}
          </div>
        </div>
      ),
    },
    {
      title: 'TP (mg/L)',
      dataIndex: 'tp',
      key: 'tp',
      width: 120,
      render: (text: string, record: any, index: number) => (
        <div>
          <div className="mb-2 min-h-5">
            {renderEditableCell(record.jinzhui?.tp, index, 'jinzhui', 'tp')}
          </div>
          <div className="mb-2 min-h-5">
            {renderEditableCell(record.chushui?.tp, index, 'chushui', 'tp')}
          </div>
          <div className="min-h-5">
            {renderEditableCell(record.quchulv?.tp, index, 'quchulv', 'tp')}
          </div>
        </div>
      ),
    },
    {
      title: '动植物油 (mg/L)',
      dataIndex: 'oil',
      key: 'oil',
      width: 140,
      render: (text: string, record: any, index: number) => (
        <div>
          <div className="mb-2 min-h-5">
            {renderEditableCell(record.jinzhui?.oil, index, 'jinzhui', 'oil')}
          </div>
          <div className="mb-2 min-h-5">
            {renderEditableCell(record.chushui?.oil, index, 'chushui', 'oil')}
          </div>
          <div className="min-h-5">
            {renderEditableCell(record.quchulv?.oil, index, 'quchulv', 'oil')}
          </div>
        </div>
      ),
    },
    {
      title: '大肠杆菌',
      dataIndex: 'ecoli',
      key: 'ecoli',
      width: 120,
      render: (text: string, record: any, index: number) => (
        <div>
          <div className="mb-2 min-h-5">
            {renderEditableCell(
              record.jinzhui?.ecoli,
              index,
              'jinzhui',
              'ecoli'
            )}
          </div>
          <div className="mb-2 min-h-5">
            {renderEditableCell(
              record.chushui?.ecoli,
              index,
              'chushui',
              'ecoli'
            )}
          </div>
          <div className="min-h-5">
            {renderEditableCell(
              record.quchulv?.ecoli,
              index,
              'quchulv',
              'ecoli'
            )}
          </div>
        </div>
      ),
    },
  ];

  return (
    <div className="w-full overflow-x-auto">
      <Table
        columns={columns}
        dataSource={tableData}
        pagination={false}
        bordered
        size="small"
        scroll={{ x: 1200 }}
        className="text-xs"
      />
    </div>
  );
}
